package com.xyh.transaction.aop;

import com.xyh.transaction.common.Current;
import com.xyh.transaction.entity.Goods;
import com.xyh.transaction.entity.GoodsStatistic;
import com.xyh.transaction.entity.User;
import com.xyh.transaction.mapper.GoodsMapper;
import com.xyh.transaction.mapper.GoodsStatisticMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class StatisticAspect {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsStatisticMapper goodsStatisticMapper;

    @Pointcut("execution(* com.xyh.transaction.service.GoodsService.getGoodsDetail(..))")
    private void goodsServicePointcut() {
    }

    @Around("goodsServicePointcut()")
    public Object goodsServiceLogAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object[] args = proceedingJoinPoint.getArgs();

        if (args.length != 1) {
            log.error("参数有误！");
            throw new IllegalArgumentException("参数有误");
        }

        User user = Current.getCurrentUser().getUser(); // userId = 0 表示是游客访问
        Goods goods = goodsMapper.findById((Integer) args[0]);
        String username = user.getUsername();

        log.info("{}访问了，{}商品详情！", username, goods.getName());
        GoodsStatistic goodsStatistic = new GoodsStatistic();
        goodsStatistic.setGoodsId(goods.getId());
        goodsStatistic.setUserId(user.getId());
        goodsStatistic.setAccessTime(LocalDateTime.now());

        goodsStatisticMapper.insert(goodsStatistic);

        return proceedingJoinPoint.proceed();
    }


}
